# -*- encoding:utf-8 -*-
from demo import app
from demo.utils.funs import *
from . import render_template, route
from flask import g, request, redirect, url_for, session, flash

from demo.models.account import Account
from demo.models.role import Role


@route('/login', methods=['GET', 'POST'])
def login():

    if request.method == 'GET':
        return render_template('/login.html')

    name = request.form.get('name')
    passwd = request.form.get('password')

    if not (name and passwd):
        return show_error('请检查用户名、密码，二者均不为空')

    account_obj = Account()
    account = account_obj.find_by({'name': [name, '=']})
    if not account:
        return show_error('用户不存在')

    if account['passwd'] != to_md5(passwd):
        return show_error('密码不正确')

    session['account'] = account
    next_url = request.args.get('next')
    if next_url:
        return redirect(next_url)
    else:
        return redirect(url_for('admin.me'))


@route('/me')
@login_required
def me():
    id = session.get('account')['id']
    account = Account().find(id)
    role = Role().find(account['role_id'])
    return render_template('/me.html', account=account, role=role)


@route('/logout')
@login_required
def logout():
    session.pop('account')
    return redirect(url_for('admin.login'))
